const App = getApp()

Page({
	data: {
		logged: !1
	},
    onLoad() {},
    onShow() {
    	const token = App.WxService.getStorageSync('token')
    	this.setData({
    		logged: !!token
    	})
    	token && setTimeout(this.goIndex, 1500)
    },
    login() {
    	this.signIn(this.goIndex)
    },
    goIndex() {
		
    	App.WxService.switchTab({
    		url: '/pages/index/index'
    	})
    },
	showModal() {
		App.WxService.showModal({
            title: '友情提示', 
            content: '获取用户登录状态失败，请重新登录', 
            showCancel: !1, 
        })
	},
	wechatSignIn(cb) {
		if (App.WxService.getStorageSync('token')) return
		App.WxService.login()
		.then(data => {
			console.log('wechatSignIn', data.code)
			return App.HttpService.wechatSignIn({
				code: data.code
			})
		})
		.then(data => {
			console.log('wechatSignIn', data)
			if (data.meta.code == 0) {
				App.WxService.setStorageSync('token', data.data.token)
				cb()
			} else if(data.meta.code == 40029) {
				App.showModal()
			} else {
				App.wechatSignUp(cb)
			}
		})
	},
	wechatSignUp(cb) {
		App.WxService.login()
		.then(data => {
			console.log('wechatSignUp', data.code)
			return App.HttpService.wechatSignUp({
				code: data.code
			})
		})
		.then(data => {
			console.log('wechatSignUp', data)
			if (data.meta.code == 0) {
				App.WxService.setStorageSync('token', data.data.token)
				cb()
			} else if(data.meta.code == 40029) {
				App.showModal()
			}
		})
	},
	signIn(cb) {
		var that=this
		wx.showToast({
			title: '登录中..',
			icon: 'loading',
			duration: 20000
			})
		wx.login({  
     		 success: function (res) {
				  console.log('微信登录成功')  
				that.apiLogin(res.code)
			  }
    		});
	},
	apiLogin(code){
		var that=this
		console.log(code)
		 wx.request({
					url: 'https://www.sjwwljs.cn/index.php/Api/User/login',
					data: {code:code},
					method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
					// header: {}, // 设置请求的 header
					success: function(res){
					  // success
					  console.log('已经执行curl')
					  console.log(res)
					  if (res.data.meta.code == 0) {
						  console.log('OK')
							wx.hideToast()
								wx.showToast({
									title: '登录成功',
									icon: 'success',
								})
								//wx.setStorageSync('user_id', res.data.data.user_id)
								//App.WxService.setStorageSync('token', res.data.data.token)
								//that.goIndex()
						}
					}, fail: function(res) {
						console.log('请求失败')
						console.log(res)
							// fail
						},
						complete: function(res) {
							// complete
							console.log('无论成功还是失败都会执行 ')
						}
					
				  })
	}
})